<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;

// 应用公共文件
function createuser($username,$coin){
    
    $ifexit2 = Db::name('users')->where('username',$username)->find();
    if($ifexit2){
        if($ifexit2['username']==$username){
            return 1038;
        }
    }


    $user = [
        'username'=>$username,
        'nickname'=>$username,
        'password'=>md5('123456'),
        'sex'=>'1',
        'avatar'=>'',
        'email'=>'',
        'mobile'=>'',
        'level'=>0,
        'birthday'=>date("Y/m/d H:i:s",time()),
        'money'=>'0.00',
        'score'=>$coin,
        'last_time'=>date("Y/m/d H:i:s",time()),
        'last_ip'=>$_SERVER['REMOTE_ADDR'],
        'join_time'=>date("Y/m/d H:i:s",time()),
        'join_ip'=>$_SERVER['REMOTE_ADDR'],
        'token'=>setToken($username),
        'created_at'=>date("Y/m/d H:i:s",time()),
        'updated_at'=>date("Y/m/d H:i:s",time()),
        'role'=>1,
        'status'=>0,

    ];
    $user_id = Db::name('users')->insertGetId($user);
    if(!$user_id){
        return 1032;
    }

    $user = getuserinfo($user_id);
    return $user;

}

function creteuseraccount($phone,$pass,$invitecode){
    $ifexit2 = Db::name('users')->where('username',$phone)->find();
    if($ifexit2){
        if($ifexit2['username']==$phone){
            return 1038;
        }
    }


    $user = [
        'username'=>$phone,
        'nickname'=>$phone,
        'password'=>md5($pass),
        'sex'=>'1',
        'avatar'=>'',
        'email'=>'',
        'mobile'=>'',
        'level'=>0,
        'birthday'=>date("Y/m/d H:i:s",time()),
        'money'=>'0.00',
        'score'=>'0.00',
        'last_time'=>date("Y/m/d H:i:s",time()),
        'last_ip'=>$_SERVER['REMOTE_ADDR'],
        'join_time'=>date("Y/m/d H:i:s",time()),
        'join_ip'=>$_SERVER['REMOTE_ADDR'],
        'token'=>setToken($phone),
        'created_at'=>date("Y/m/d H:i:s",time()),
        'updated_at'=>date("Y/m/d H:i:s",time()),
        'role'=>1,
        'status'=>0,
        'invitecode'=>createinvitecode(),
        'teams'=>0
    ];
    $user_id = Db::name('users')->insertGetId($user);
    if(!$user_id){
        return 1032;
    }
    // 绑定上级
    $bind = bindagent($user_id,$invitecode);

    $user = getuserinfo($user_id);
    return $user;
}

function bindagent($user_id,$invitecode){
    $ifexit = Db::name('users')->where('invitecode',$invitecode)->find();
    if($ifexit){
        $agent_id = $ifexit['id'];
        $agent = Db::name('agents')->insert([
            'uid'=>$user_id,
            'oneuid'=>$agent_id,
            'addtime'=>time()
        ]);
        // 查出所有团队的人数都加1
        $upteams = upteams($user_id);
        if(!$agent){
            return 1033;
        }
        return 1;
    }
}

function upteams($uid){
    $list = [];
    $list = getallagents($uid,$list);
    foreach($list as $k=>$v){
        Db::name("users")->where('id',$v)->setInc('teams',1);
    }
}

// 获取所有上级列表
function getallagents($uid, $list){
 
    $top=Db::name("agents")->where('uid',$uid)->find();
		// var_dump($top);
    if($top)
    {
        $topid=$top['oneuid'];
        $list[]=$topid;
        return getallagents($topid,$list);
    }else{
        return $list;
    }
}

function getxiajiall($uid,$list){

}
function handlewan($num){
    if($num < 10000){
        return $num;
    }
    $result = $num /10000;
    return round($result,2).'万';
}


function createinvitecode(){
    // 生成不重复的六位邀请码
    $invitecode = '';
    $code = '0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ';
    $code_len = strlen($code) - 1;
    for ($i = 0; $i < 6; $i++) {
        $invitecode .= $code[mt_rand(0, $code_len)];
    }
    return $invitecode;
    
}
// 获取用户信息
function getuserinfo3($uid){
    $ifexit = Db::name("users")->where("username",$uid)->find();
    $user['id']=$ifexit['id'];
    $user['username']=$ifexit['username'];
    $user['nickname']=$ifexit['nickname'];
    $user['score']=$ifexit['score'];
    $user['money']=$ifexit['money'];
    $user['isrobot']=$ifexit['isrobot'];
    $user['status']=$ifexit['status'];
    $user['roomid']=$ifexit['roomid'];
    $user['invitecode']=$ifexit['invitecode'];
    $user['teams']=$ifexit['teams'];
    $user['shareurl']=getconfig("shareurl");
    return $user;
}
function getuserinfo($uid){
    $user = Db::name('users')->where('id',$uid)->field('id,username,money,score,token,invitecode,teams')->find();
    $user['shareurl']=getconfig("shareurl");

    return $user;
}


function getuserinfo2($username){
    $user = Db::name('users')->where('username',$username)->field('id,username,score,token,invitecode,teams')->find();
    return $user;
}
function setToken($phone){
    $str = md5(uniqid(md5(microtime(true)),true));
    $token = sha1($str.$phone);
    return $token;
}

function get_client_ip()
{
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) {
            unset($arr[$pos]);
        }
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip; 
}
function checksign($data,$sign){

    $sign2 = makesign($data);
    // var_dump($sign2,$sign);die;
    if($sign2 == $sign){
        return true;
    }else{
        return false;
    }
}

function makesign($data){
    // var_dump($data);die;
    $key = config("apikey");
    $p =ksort($data);
    if($p){
        $str = '';
        foreach ($data as $k=>$val){
            $str  .=  $k  .'='  .  $val  .  '&';
        }
         $strs = rtrim($str, '&');
    }
    
    $sign2 = md5($strs.'&key='.$key);
// var_dump($sign2);die;
    return  $sign2;
}


function makesign22($data){
    // var_dump($data);die;
    $key = '6341064449';

    $str = '';
    foreach ($data as $k=>$val){
        $str  .=  $k  .'='  .  $val  .  '&';
    }
    $strs = rtrim($str, '&');
    // var_dump($strs.'&transactionKey='.$key);
    $sign2 = md5($strs.'&transactionKey='.$key);

    return  $sign2;
}

    /* 
     * curl发送post请求	
     * url:访问路径  
     * array:要传递的数组  
     * */  
        /**
	 * 发送post请求
	 * @param string $url 请求地址
	 * @param array $post_data post键值对数据
	 * @return string
	 */
	function sendpost($url, $post_data) {
        // var_dump($url,$post_data);die;

		// $postdata = http_build_query($post_data);
        // var_dump($post_data);die;
		$options = array(
		    'http' => array(
			'method' => 'POST',
			'header' => 'Content-type:application/json',
			'content' => $post_data,
			'timeout' => 120 // 超时时间（单位:s）
		)
	  );
		$context = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
		return $result;
	}	
        /* 
     * curl发送post请求	
     * url:访问路径  
     * array:要传递的数组  
     * */  
    function curl_post($url,$array){  
		$curl = curl_init();  
		//设置提交的url
		curl_setopt($curl, CURLOPT_URL, $url);  
		//设置头文件的信息作为数据流输出  
		curl_setopt($curl, CURLOPT_HEADER, 0);  
		//设置获取的信息以文件流的形式返回，而不是直接输出  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
		//设置post方式提交  
		curl_setopt($curl, CURLOPT_POST, 1);
		// 最大执行时间超时时间（单位:s）
		curl_setopt($curl, CURLOPT_TIMEOUT, 120);			
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, $array);  
		//执行命令
		$data = curl_exec($curl);
		//获得数据并返回
		return $data;
		//关闭URL请求
		curl_close($curl);
    }
    function getconfig($name){
        $option = Db::name("options")->where("id",1)->find();
        $res = json_decode($option['value'],1);

        return $res['logo'][$name];
    }

    function handleimage($image){
        $siteurl = getconfig("siteurl");
        $image = $siteurl.$image;
        return $image;
    }
    function returnresbonse($code,$msg,$data){
        $res = array(
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data);
        echo json_encode($res);exit();
    }

    function comparepass($pass,$mypass){
        if(md5($pass) != $mypass){
            return false;
        }else{
            return true;
        }
    }


    function updatetoken($phone){
        $str = md5(uniqid(md5(microtime(true)),true));
        $token = sha1($str.$phone);
        Db::name("users")->where("username",$phone)->update(['token'=>$token]);

        return $token;
    }

    function returnjson($code,$msg,$data){
        $res = ['code'=>$code,'msg'=>$msg,'data'=>$data];
        return json($res);exit();
    }
    function checkcode($code){
        $user = Db::name("users")->where("invitecode",$code)->find();
        if(!$user){
            return false;
        }else{
            return true;
        }
    }
    function checktoken($uid,$token){
        $user = Db::name('users')->where("id",$uid)->value('token');
        //    var_dump($user,$token);
           if(!$user){
                $data=[
                    'code'=>10020,
                    'msg'=>'用户不存在',
                    'info'=>''
                ];
                return 700;
           }
           if($user && $user!= $token){
            $data=[
                'code'=>700,
                'msg'=>'您的登录已过期，请重新登录',
                'info'=>''
            ];
                return 700;
           }
           return 1;
    
    }
    // coin = score ,     type:1加   2剪   ,remark 备注
    function upusercoin($uid,$coin,$type,$remark){
        $user = Db::name('users')->where("id",$uid)->find();
        if($type==1){
            $user['score'] = $user['score'] + $coin;
            $paytype = 1;
        }else{
            $user['score'] = $user['score'] - $coin;
            $paytype = 0;
        }
        $up = Db::name('users')->where("id",$uid)->update(['score'=>$user['score']]);

        if($up){
            $data=[
                'uid'=>$uid,
                'coin'=>$coin,
                'type'=>$paytype,
                'remark'=>$remark,
                'addtime'=>date('Y-m-d H:i:s',time()),
            ];
           $record =  Db::name("usercoin_record")->insert($data);
           if($record){
                return 1;
           }else{
                return 0;
           }
            
        }else{
            return 0;
        }

    }